package com.taniurakengo.sourceviewer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import com.taniurakengo.sourceviewer.DocumentHandler.CSharpDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.CppDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.CssDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.DocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.HtmlDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.JavaDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.PhpDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.PlainDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.PythonDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.RubyDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.ScalaDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.SqlDocumentHandler;
import com.taniurakengo.sourceviewer.DocumentHandler.VbDocumentHandler;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

public class WebViewFragment extends Fragment{

	private WebView mWebView;
	private TextView mTitle;
	private TextView mSummary;
	private String keyword;
	private String summary;
	private String currentpath;
	
	/**
	 * 
	 * @param _keyword
	 * @param _summary
	 * @return
	 */
    public static WebViewFragment newInstance(String _keyword, 
    										  String _summary,
    										  String _currentpath) {  

		try {
			WebViewFragment flagment = new WebViewFragment();
			Bundle args = new Bundle();  
			args.putString("keyword", _keyword);
			args.putString("summary", _summary);
			args.putString("currentpath", _currentpath);
			
			flagment.setArguments(args);
			return flagment;
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
        return null;  
    }  
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		
	}
	
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }	

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(
							LayoutInflater inflater,
							ViewGroup container,
							Bundle savedInstanceState) {
		
        Bundle args = getArguments();
        keyword = args.getString("keyword");
        summary = args.getString("summary");
        currentpath = args.getString("currentpath");
        
        View layout = inflater.inflate(R.layout.sourceview_acitvity, container, false);
		try {
            
            //findViewById
			mWebView = (WebView) layout.findViewById(R.id.webview1);
    		mTitle = (TextView) layout.findViewById(R.id.title1);
    		mSummary = (TextView) layout.findViewById(R.id.summary1);

//    		mWebView.setWebViewClient(new CustomWebViewClient());
    		
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            webSettings.setUseWideViewPort(false);
            webSettings.setAllowFileAccess(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setLightTouchEnabled(true);
            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setSupportZoom(true);
            webSettings.setSupportMultipleWindows(true);
            webSettings.setJavaScriptEnabled(true);
            
	    	File file = new File(keyword);
	    	
	    	//file？
	    	if(file.isFile()){

	    		//Preferences
	        	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
	        	String characterCode = pref.getString("CHARSET", "UTF-8");
	        	String css_style = pref.getString("CSS_STYLE", "shThemeDefault.css");
	        	
    			String title = file.getPath().replace(currentpath, "");
    			if (title.equals("")){
    				title = file.getName();
    			}
    			mTitle.setText(title);
    			mSummary.setText("(" +summary + ")");

    			//Get DocumentHandler
    			DocumentHandler handler = null;
    			if (file.getName().endsWith(".c") || file.getName().endsWith(".cpp") || file.getName().endsWith(".cc")) handler = new CppDocumentHandler();
    			if (file.getName().endsWith(".m") || file.getName().endsWith(".h")) handler = new CppDocumentHandler();
    			if (file.getName().endsWith(".cs")) handler = new CSharpDocumentHandler();
    			if (file.getName().endsWith(".css")) handler = new CssDocumentHandler();
    			if (file.getName().endsWith(".java")) handler = new JavaDocumentHandler();
    			if (file.getName().endsWith(".pl")) handler = new PythonDocumentHandler();
    			if (file.getName().endsWith(".php")) handler = new PhpDocumentHandler();
    			if (file.getName().endsWith(".py")) handler = new PythonDocumentHandler();
    			if (file.getName().endsWith(".rb")) handler = new RubyDocumentHandler();
    			if (file.getName().endsWith(".scala")) handler = new ScalaDocumentHandler();
    			if (file.getName().endsWith(".sql")) handler = new SqlDocumentHandler();
    			if (file.getName().endsWith(".vb") || file.getName().endsWith(".bas")) handler = new VbDocumentHandler();
    			if (file.getName().endsWith(".html") || file.getName().endsWith(".htm")) handler = new HtmlDocumentHandler();
    			if (file.getName().endsWith(".xml") || file.getName().endsWith(".xhtm")) handler = new HtmlDocumentHandler();
    			if (file.getName().endsWith(".storyboard")) handler = new HtmlDocumentHandler();
    			if (handler == null) handler = new PlainDocumentHandler();
    			
    			//webview source
    			StringBuilder src = new StringBuilder();

    			String html = "<?xml version=\"1.0\" encoding=\"#encoding#\"?>";
    			html.replace("#encording#", characterCode);
    			src.append(html);
    			
    			src.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
    			src.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"ja\" lang=\"ja\">");
    			src.append("<head>");
    			
    			html = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=#encording#\" />";
    			html.replace("#encording#", characterCode);
    			src.append(html);    			

    			src.append("<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />");
    			src.append("<meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\" />");
    			src.append("<link type=\"text/css\" rel=\"stylesheet\" href=\"file:///android_asset/styles/shCore.css\" />");
    			src.append("<link type=\"text/css\" rel=\"stylesheet\" href=\"file:///android_asset/styles/" + css_style + "\" />");
    			src.append("<script type=\"text/javascript\" src=\"file:///android_asset/scripts/shCore.js\"></script>");
    			src.append(handler.getBrushFileName());
    			src.append("<script type=\"text/javascript\">");
    			src.append("  SyntaxHighlighter.all();");
    			src.append("  SyntaxHighlighter.defaults['auto-links'] = false;");
    			src.append("</script></head>");
    			
    			if (css_style.equals("shThemeDefault.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreDefault) + "\" >");
    			if (css_style.equals("shThemeDjango.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreDjango) + "\" >");
    			if (css_style.equals("shThemeEclipse.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreEclipse) + "\" >");
    			if (css_style.equals("shThemeEmacs.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreEmacs) + "\" >");
    			if (css_style.equals("shThemeFadeToGrey.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreFadeToGrey) + "\" >");
    			if (css_style.equals("shThemeMDUltra.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreMDUltra) + "\" >");
    			if (css_style.equals("shThemeMidnight.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreMidnight) + "\" >");
    			if (css_style.equals("shThemeRDark.css")) src.append("<body  bgcolor=\"" + getResources().getString(R.string.CoreRDark) + "\" >");
    			
    	        src.append(handler.getBrushAlieses());

    	        //read file
	        	BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),characterCode));
    			String str="";
    			while ((str = reader.readLine()) != null) {
    				src.append(str + "\n");
    	        }
    			reader.close();

    			src.append("</pre></body></html>");
    			
    			mWebView.loadDataWithBaseURL("file:///android_asset/", src.toString(), "text/html","UTF-8", null);
    			
	    	}else{
	    		
	    	}
    	    	

		}catch(FileNotFoundException e){
			System.out.println(e.toString());
		}catch(IOException e){
			System.out.println(e.toString());
		}catch(Exception e) {
			System.out.println(e.toString());
		}
		
        return layout;
	}
	
}
